/*
Copyright 2024 MySQL Parser Project

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package sqlparser

import (
	"strings"
	"sync"
)

// Global parser instance
var (
	defaultParser *Parser
	parserOnce    sync.Once
)

// getDefaultParser returns the default parser instance
func getDefaultParser() *Parser {
	parserOnce.Do(func() {
		var err error
		defaultParser, err = New(Options{
			MySQLServerVersion: "5.7.0",
		})
		if err != nil {
			panic(err)
		}
	})
	return defaultParser
}

// Parse parses a SQL string and returns the AST using the default parser
func Parse(sql string) (Statement, error) {
	return getDefaultParser().Parse(sql)
}

// ParseExpr parses an expression and returns the AST using the default parser
func ParseExpr(sql string) (Expr, error) {
	return getDefaultParser().ParseExpr(sql)
}

// ParseNext parses multiple SQL statements
func ParseNext(tokenizer *Tokenizer) (Statement, error) {
	if yyParse(tokenizer) != 0 {
		if tokenizer.lastError != nil {
			return nil, tokenizer.lastError
		}
		return nil, nil
	}
	return tokenizer.ParseTree, nil
}

// SplitStatement splits a multi-statement SQL string into individual statements
func SplitStatement(sql string) ([]string, error) {
	var statements []string
	tokenizer := NewStringTokenizer(sql)
	
	var current strings.Builder
	for {
		tok, val := tokenizer.Scan()
		if tok == 0 {
			break
		}
		
		if tok == int(SEMICOLON) {
			if current.Len() > 0 {
				statements = append(statements, strings.TrimSpace(current.String()))
				current.Reset()
			}
		} else {
			if current.Len() > 0 {
				current.WriteString(" ")
			}
			current.WriteString(val)
		}
	}
	
	if current.Len() > 0 {
		statements = append(statements, strings.TrimSpace(current.String()))
	}
	
	return statements, nil
}

// IsDML returns true if the SQL statement is a DML statement
func IsDML(sql string) bool {
	tokenizer := NewStringTokenizer(sql)
	tok, _ := tokenizer.Scan()
	
	switch tok {
	case int(SELECT), int(INSERT), int(UPDATE), int(DELETE):
		return true
	default:
		return false
	}
}

// IsDDL returns true if the SQL statement is a DDL statement
func IsDDL(sql string) bool {
	tokenizer := NewStringTokenizer(sql)
	tok, _ := tokenizer.Scan()
	
	switch tok {
	case int(CREATE), int(ALTER), int(DROP), int(TRUNCATE):
		return true
	default:
		return false
	}
}

// IsTransactionControl returns true if the SQL statement is a transaction control statement
func IsTransactionControl(sql string) bool {
	tokenizer := NewStringTokenizer(sql)
	tok, _ := tokenizer.Scan()
	
	switch tok {
	case int(BEGIN), int(COMMIT), int(ROLLBACK):
		return true
	default:
		return false
	}
}

// GetStatementType returns the type of SQL statement
func GetStatementType(sql string) string {
	tokenizer := NewStringTokenizer(sql)
	tok, val := tokenizer.Scan()
	
	if tok == 0 {
		return "UNKNOWN"
	}
	
	return strings.ToUpper(val)
}

// StripComments removes comments from SQL
func StripComments(sql string) string {
	var result strings.Builder
	tokenizer := NewStringTokenizer(sql)
	
	for {
		tok, val := tokenizer.Scan()
		if tok == 0 {
			break
		}
		
		if tok != int(COMMENT) {
			if result.Len() > 0 {
				result.WriteString(" ")
			}
			result.WriteString(val)
		}
	}
	
	return strings.TrimSpace(result.String())
}

// Normalize normalizes a SQL statement by removing extra whitespace and comments
func Normalize(sql string) string {
	return StripComments(sql)
}